#!/usr/bin/env bash

declare -r VERSION=2.7.1
declare -r IMAGE=/app/data/k8s/docker-images/registry_${VERSION}.image.tar
declare -r STORAGE=/app/registry
declare -r SSL_DIR=/app/ssl/registry
declare -r DOCKER_HUB=docker-hub:5000

echo "Checking registry running..."
docker ps -a | grep '\ registry$' > /dev/null
if [ $? -eq 0 ]; then
  echo "Stop & Remove previous registry..."
  docker stop registry > /dev/null
  docker rm registry > /dev/null
fi

echo "Checking registry image exists..."
declare -ri RET=$(docker images registry:${VERSION} | wc -l)
if [ ${RET} -eq 1 ]; then
  echo "Loading registry image file..."
  docker load -i ${IMAGE}
fi

echo "Checking directory exists..."
if [[ -d ${STORAGE} ]]; then
  echo "  directory exists!"
else
  mkdir -pv ${STORAGE}
  echo ""
fi

echo "Starting private registry server on secure mode..."
docker run -d -m 512m --restart=always \
  --name=registry \
  -p 5000:5000 \
  -v ${STORAGE}:/var/lib/registry \
  -v ${SSL_DIR}:/certs:ro \
  -v ${SSL_DIR}/registry.yml:/etc/docker/registry/config.yml:ro \
  -e TZ=Asia/Shanghai \
  -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/registry.pem \
  -e REGISTRY_HTTP_TLS_KEY=/certs/registry.key \
  -e REGISTRY_STORAGE_DELETE_ENABLED=true \
  registry:${VERSION}

echo -e "Started!\n"

docker container ps
